//
//  AppUtil.swift
//  ReportScan
//
//  Created by woniu on 2025/7/22.
//

import Foundation

struct AppUtil {
    
    //读取json文件
    public static func getJsonFileString()->String{
        // 获取文件路径
        if let filePath = Bundle.main.path(forResource: "test", ofType: "json") {
            do {
                // 读取文件内容
                let fileContent = try String(contentsOfFile: filePath, encoding: .utf8)
                return fileContent
            } catch {
                return ""
            }
        }
        return ""
    }
    
    
    /// 获取CSV文件、读取CSV文件 、 遍历CSV文件
    /// - Parameter isDropFirst: 是否跳过第一行，有些第一行是标题行
    public static func getCSVFile(isDropFirst:Bool,fileUrl:URL?)->[[String]]{
        
        do {
            var content = ""
            //从指定文件读取
            if let flieUrl = fileUrl{
                content = try String(contentsOf: flieUrl, encoding: .utf8)
                
            }else{
                //读取本地文件
                guard let csvFilePath = Bundle.main.path(forResource: "test", ofType: "json") else {
                    print("文件获取失败")
                    return []
                }
                content = try String(contentsOfFile: csvFilePath,encoding: .utf8)
            }
            
            let lines = content.components(separatedBy: .newlines)
            var dataArray:[[String]] = []
            // 跳过标题行
            if isDropFirst{
                for line in lines.dropFirst() where !line.isEmpty {
                    let rowArray = line.components(separatedBy: ",")
                    var subArr:[String] = []
                    for item in rowArray{
                        subArr.append(item)
                    }
                    dataArray.append(subArr)
                }
            }else{
                for line in lines where !line.isEmpty {
                    let rowArray = line.components(separatedBy: ",")
                    var subArr:[String] = []
                    for item in rowArray{
                        subArr.append(item)
                    }
                    dataArray.append(subArr)
                }
            }
            print("总共:\(dataArray.count)条数据")
            return dataArray
            
        } catch {
            print("加载CSV失败: \(error)")
            return []
        }
    }
}
